package com.wnnight.wys.filter;

import com.wnnight.wys.security.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtExpireFilter implements Filter {

    @Autowired
    private JwtUtils jwtUtils;

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if (req.getHeader("jwt") != null) {
            String jwt = req.getHeader("jwt");
            int id = (int) JwtUtils.getInfo(jwt, "id");
            String account = (String) JwtUtils.getInfo(jwt, "account");
            int roleId = (int) JwtUtils.getInfo(jwt, "roleId");
            jwt = jwtUtils.creatJWT(id, account, roleId);
            resp.setHeader("jwt", jwt);
        }
        chain.doFilter(request, response);
    }
}
